/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.func;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.func.funcPerm.fastAuth.FuncQuickPermission;
import com.je.common.base.service.MetaDataPermCheckService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.meta.service.func.FuncQuickPermissionDeleteValidService;
import com.je.meta.service.func.FuncQuickPermissionUpdateValidService;
import com.je.meta.service.permission.*;
import com.je.rbac.rpc.DepartmentUserRpcService;
import com.je.rbac.rpc.RoleRpcService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import sun.security.x509.AuthorityKeyIdentifierExtension;

import java.util.List;

@RpcSchema(schemaId = "metaDataPermCheckRpcService")
public class MetaDataPermCheckRpcServiceImpl implements MetaDataPermCheckService {

    @Autowired
    private FuncQuickPermissionUpdateValidService funcQuickPermissionUpdateValidService;
    @Autowired
    private FuncQuickPermissionDeleteValidService funcQuickPermissionDeleteValidService;
    @Autowired
    private MetaFuncPermService metaFuncPermService;
    @Autowired
    private PcFuncSelfDataService pcFuncSelfDataService;
    @Autowired
    private PcFuncDeptLeaderDataService pcFuncDeptLeaderDataService;
    @Autowired
    private PcFuncDirectLeaderDataService pcFuncDirectLeaderDataService;
    @Autowired
    private PcFuncMyDeptDataService pcFuncMyDeptDataService;
    @Autowired
    private PcFuncMonitorLeaderDataService pcFuncMonitorLeaderDataService;
    @Autowired
    private PcFuncMonitorCompanyDataService pcFuncMonitorCompanyDataService;
    @Autowired
    private PcFuncDeptMonitorDeptDataService pcFuncDeptMonitorDeptDataService;
    @Autowired
    private PcFuncCompanyDataService pcFuncCompanyDataService;
    @Autowired
    private PcFuncGroupCompanyDataService pcFuncGroupCompanyDataService;
    @Autowired
    private PcFuncMyApprovePendingDataService pcFuncMyApprovePendingDataService;
    @Autowired
    private PcFuncMyApprovePendedDataService pcFuncMyApprovePendedDataService;
    @Autowired
    private RoleRpcService roleRpcService;
    @Autowired
    private DepartmentUserRpcService departmentUserRpcService;

    @Override
    public boolean validUpdatePermission(String funcCode, DynaBean dynaBean) {
        FuncQuickPermission funcQuickPermission = metaFuncPermService.getFuncQuickPermission(funcCode);
        return funcQuickPermissionUpdateValidService.validUpdatePermission(funcCode, funcQuickPermission, dynaBean);
    }

    @Override
    public boolean validDeletePermission(String funcCode, DynaBean dynaBean) {
        FuncQuickPermission funcQuickPermission = metaFuncPermService.getFuncQuickPermission(funcCode);
        return funcQuickPermissionDeleteValidService.validDeletePermission(funcCode, funcQuickPermission, dynaBean);
    }

    @Override
    public String outputQuickQuerySql(String funcCode) {
        FuncQuickPermission funcQuickPermission = metaFuncPermService.getFuncQuickPermission(funcCode);
        StringBuffer sb = new StringBuffer();
        //没有开启，则直接返回
        if (funcQuickPermission == null || !funcQuickPermission.isActive() || SecurityUserHolder.getCurrentAccount() == null) {
            return null;
        }

        boolean seePriority = false;
        //可见人员
        if (funcQuickPermission.isUserControlQuery() && funcQuickPermission.getSeeUserIdList() != null
                && !funcQuickPermission.getSeeUserIdList().isEmpty()
                && funcQuickPermission.getSeeUserIdList().contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
            seePriority = true;
        }

        //可见部门
        if (!seePriority && funcQuickPermission.isDeptControlQuery() && funcQuickPermission.getSeeDeptIdList() != null
                && !funcQuickPermission.getSeeDeptIdList().isEmpty()
                && funcQuickPermission.getSeeDeptIdList().contains(SecurityUserHolder.getCurrentAccountRealOrgId())) {
            seePriority = true;
        }

        //可见角色
        if (!seePriority && funcQuickPermission.isRoleControlQuery()) {
            List<String> userIdList = roleRpcService.findRoleUserIds(funcQuickPermission.getSeeRoleIdList());
            if (userIdList != null && !userIdList.isEmpty() && userIdList.contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
                seePriority = true;
            }
        }

        //可见机构
        if (!seePriority && funcQuickPermission.isOrgControlQuery()) {
            if (funcQuickPermission.getSeeOrgIdList() != null && !funcQuickPermission.getSeeOrgIdList().isEmpty()
                    && funcQuickPermission.getSeeOrgIdList().contains(SecurityUserHolder.getCurrentAccount().getPlatformOrganization().getId())) {
                seePriority = true;
            }
        }

        if (seePriority) {
            return null;
        }

        sb.append(pcFuncSelfDataService.formatFuncDataSelfShowOutput(funcQuickPermission.getCreateUserIdField(), SecurityUserHolder.getCurrentAccountRealUserId()));
        //部门领导
        if (funcQuickPermission.isDeptHeadQuery()) {
            List<String> majorList = departmentUserRpcService.findDeptLeaderIds(SecurityUserHolder.getCurrentAccountRealOrgId());
            if (majorList != null && majorList.contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
                sb.append(" OR ");
                sb.append(pcFuncDeptLeaderDataService.formatFuncDataDeptLeaderShowOutput(funcQuickPermission.getCreateDeptIdField(), SecurityUserHolder.getCurrentAccountRealOrgId()));
            }
        }

        //直接领导
        if (funcQuickPermission.isDirectLeaderQuery()) {
            List<String> userIdList = departmentUserRpcService.findDirectUserIds(SecurityUserHolder.getCurrentAccountRealOrgId(), SecurityUserHolder.getCurrentAccountRealUserId());
            if (userIdList != null && !userIdList.isEmpty() && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountRealOrgId())) {
                sb.append(" OR ");
                sb.append(pcFuncDirectLeaderDataService.formatFuncDataDirectLeaderShowOutput(funcQuickPermission.getCreateDeptIdField(), funcQuickPermission.getCreateUserIdField(), SecurityUserHolder.getCurrentAccountRealOrgId(), userIdList));
            }
        }

        //本部门
        if (funcQuickPermission.isMyDeptQuery()) {
            if (!Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountRealOrgId())) {
                sb.append(" OR ");
                sb.append(pcFuncMyDeptDataService.formatFuncDataMyDeptShowOutput(funcQuickPermission.getCreateDeptIdField(), SecurityUserHolder.getCurrentAccountRealOrgId()));
            }
        }

        //监管领导
        if (funcQuickPermission.isMonitorLeaderQuery() && SecurityUserHolder.getCurrentAccountRealDepartmentUser() != null) {
            List<String> monitDeptList = departmentUserRpcService.findMonitorDeptIds(SecurityUserHolder.getCurrentAccountRealOrgId(), SecurityUserHolder.getCurrentAccountRealUserId());
            if (monitDeptList != null && !monitDeptList.isEmpty()) {
                sb.append(" OR ");
                sb.append(pcFuncMonitorLeaderDataService.formatFuncDataMonitorLeaderShowOutput(funcQuickPermission.getCreateDeptIdField(), monitDeptList));
            }
        }

        //部门间监管
        if (funcQuickPermission.isDeptMonitorDeptQuery() && SecurityUserHolder.getCurrentAccountDepartment() != null) {
            List<String> deptMonitorDeptIdList = departmentUserRpcService.findDeptMonitorDeptIds(SecurityUserHolder.getCurrentAccountRealOrgId());
            if (deptMonitorDeptIdList != null && !deptMonitorDeptIdList.isEmpty()) {
                sb.append(" OR ");
                sb.append(pcFuncDeptMonitorDeptDataService.formatFuncDataDeptMonitorDeptShowOutput(funcQuickPermission.getCreateDeptIdField(), deptMonitorDeptIdList));
            }
        }

        //公司内
        if (funcQuickPermission.isMyCompanyQuery() && SecurityUserHolder.getCurrentAccountDepartment() != null) {
            if (SecurityUserHolder.getCurrentAccountDepartment() != null && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId())) {
                sb.append(" OR ");
                sb.append(pcFuncCompanyDataService.formatFuncDataCompanyShowOutput(funcQuickPermission.getCompanyIdFieldCode(), SecurityUserHolder.getCurrentAccountDepartment().getCompanyId()));
            }
        }

        //集团公司内可见
        if (funcQuickPermission.isGroupCompanyQuery() && SecurityUserHolder.getCurrentAccountDepartment() != null) {
            if (SecurityUserHolder.getCurrentAccountDepartment() != null && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountDepartment().getGroupCompanyId())) {
                sb.append(" OR ");
                sb.append(pcFuncGroupCompanyDataService.formatFuncDataGroupCompanyShowOutput(funcQuickPermission.getGroupCompanyIdFieldCode(), SecurityUserHolder.getCurrentAccountDepartment().getGroupCompanyId()));
            }
        }

        //公司监管
        if (funcQuickPermission.isMonitorCompanyQuery() && SecurityUserHolder.getCurrentAccountRealDepartmentUser() != null) {
            if (SecurityUserHolder.getCurrentAccountDepartment() != null && !Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId())) {
                List<String> companyMonitorCompanyIds = departmentUserRpcService.findCompanyMonitorCompanyIds(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId());
                if (companyMonitorCompanyIds != null && !companyMonitorCompanyIds.isEmpty()) {
                    sb.append(" OR ");
                    sb.append(pcFuncMonitorCompanyDataService.formatFuncDataMonitorCompanyShowOutput(funcQuickPermission.getCompanyIdFieldCode(), companyMonitorCompanyIds));
                }
            }
        }

        //待审批可见
        if (funcQuickPermission.isApproPreQuery()) {
            if (!Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccount().getDeptId())) {
                sb.append(" OR ");
                sb.append(pcFuncMyApprovePendingDataService.formatFuncDataMyApprovePendingShowOutout(SecurityUserHolder.getCurrentAccount().getDeptId()));
            }
        }

        //审批后可见
        if (funcQuickPermission.isApproAfterQuery()) {
            if (!Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccount().getDeptId())) {
                sb.append(" OR ");
                sb.append(pcFuncMyApprovePendedDataService.formatFuncDataMyApprovePendedShowOutput(SecurityUserHolder.getCurrentAccount().getDeptId()));
            }
        }

        String whereSql = sb.toString();
        if (StringUtil.isNotEmpty(whereSql)) {
            if (whereSql.trim().startsWith("OR")) {
                whereSql = whereSql.trim().replaceFirst("OR", "");
            }
        }
        return whereSql;
    }
}
